﻿using PLCS.Domain.Tasks;
using PLCS.EntityFrameworkCore.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLCS.EntityFrameworkCore.Tasks
{
    public class InstructionRepository : EfCoreRepository<PLCSDbContext, Instruction, Guid>, IInstructionRepository
    {
        public InstructionRepository(IDbContextProvider<PLCSDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task ChangeStatusAsync(Guid Id, Domain.Shared.Tasks.InstructionStatus taskStatus)
        {
            var dbContext = await GetDbContextAsync();
            var instruction = await dbContext.Instructions.Where(x => x.Id == Id).FirstOrDefaultAsync();
            Check.NotNull(instruction, Id.ToString(), $"不存在指令:{Id}");
            instruction.ChangeStatus(taskStatus);
            await dbContext.SaveChangesAsync();
        }

        public async Task<IEnumerable<Instruction>> GetUnfinishedInstructionsAsync(string equipmentNo)
        {
            var queryable = await GetQueryableAsync();
            queryable = queryable.Include(x => x.Task)
            .Where(x => x.EquipmentNo == equipmentNo)
            .Where(x => x.Status == Domain.Shared.Tasks.InstructionStatus.未执行 || x.Status == Domain.Shared.Tasks.InstructionStatus.执行中);
            return await AsyncExecuter.ToListAsync(queryable);
        }

        public async Task<IEnumerable<Instruction>> GetUnfinishedInstructionsAsync()
        {
            var queryable = await GetQueryableAsync();
            queryable = queryable.Include(x => x.Task);
            return await AsyncExecuter.ToListAsync(queryable);
        }

        public async Task HardDeleteAsync(int instructionNo)
        {
            var dbContext = await GetDbContextAsync();
            await dbContext.Database.ExecuteSqlRawAsync($"Delete from T_Instructions where InstructionNo = '{instructionNo}'");
        }
    }
}